package org.test.java;

import static org.test.java.ShuaTa.httpRequestWithLogFile;
import static org.test.java.ShuaTa.print;
import static org.test.java.ShuaTa.sleepTime;

import java.io.IOException;
import java.util.Map;
import java.util.Properties;

public class Boss implements Runnable {

	private String _sid;
	Properties props;
	private static String logFile = "boss.log";

	public Boss(String _sid, Properties props) {
		this._sid = _sid;
		this.props = props;
		if (props.containsKey("bossLogFile")) {
			logFile  = props.getProperty("bossLogFile");
		}
		if (props.containsKey("shuaTaSleepTime")) {
			sleepTime = Integer.parseInt(props.getProperty("shuaTaSleepTime"));
		}
	}

	@Override
	public void run() {
		int temp = 0;
		while (true) {
			try {
				try {
					if (temp >= 1)
						Thread.sleep(1 * 60 * 1000);
					temp++;
				} catch (InterruptedException e1) {
					e1.printStackTrace();
					try {
						log(e1.getMessage());
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				while (true) {

					Map result = httpRequestWithLogFile(_sid, "boss.php", "GetBoss", "", logFile);
					int status = Double.valueOf(result.get("status").toString()).intValue();
					if (status == 0){
						log("Boss不可战斗。");
						continue;
					}
					Map data = (Map) result.get("data");
					log(data.toString());
					Map boss = (Map) data.get("Boss");
					int currentHp = Double.valueOf(boss.get("BossCurrentHp").toString()).intValue();
					if(currentHp <= 0){
						log("Boss血量为0.退出，等待每一定时间检测Boss。");
						break;
					}
					log("Get boss fight time.");
					int waitTime = ((Double) data.get("CanFightTime"))
							.intValue();
					if(waitTime > 0){
						log("等待可战斗时间：" + waitTime + "s");
						Thread.sleep(waitTime * 1000);
					}
					log("To fight with boss.");
					Map fightResult = httpRequestWithLogFile(_sid, "boss.php", "Fight", "", logFile);
					log(fightResult.toString());
				}
			} catch (Exception e) {
				e.printStackTrace();
				try {
					log(e.getMessage());
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
	}

	private void log(String result) throws IOException {
		print(logFile, result);
	}

}
